package org.yu.team2023.flashdays.net;

import lombok.RequiredArgsConstructor;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.Level;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import org.yu.team2023.flashdays.ModBlockEntities;
import org.yu.team2023.flashdays.blockentity.TreasureUpgradeEntity;

import java.util.Optional;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class TreasureUpgradeRequestPackage {
    private final BlockPos blockPos;


    public void toBytes(FriendlyByteBuf buf) {
        buf.writeBlockPos(blockPos);
    }

    public static TreasureUpgradeRequestPackage create(FriendlyByteBuf buf) {
        return new TreasureUpgradeRequestPackage(buf.readBlockPos());
    }

    public void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            if (context.getDirection().getReceptionSide() == LogicalSide.SERVER) {
              ServerPlayer player= context.getSender();
              if(player!=null&&player.isAlive()){
                  Level world=player.level();
                  Optional<TreasureUpgradeEntity> be=world.getBlockEntity(blockPos, ModBlockEntities.BlockEntities.TREASURE_UPGRADE_ENTITY.get());
                  be.ifPresent(TreasureUpgradeEntity::upgradeOnServer);
              }
            }
        });
        context.setPacketHandled(true);
    }


}

